﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;

namespace AMInstantMessagingService
{
    public class ConfigSettings
    {
        /// <summary>
        /// xmlnode 获取器
        /// </summary>
        public Func<XmlDocument, string, string> XmlNodeGetter { get; set; }

        public ConfigSettings()
        {
            XmlDocument = new XmlDocument();

            string file_path = Path.Combine(Directory.GetCurrentDirectory(), Assembly.GetEntryAssembly().GetName().Name + ".dll.Config");

            if (File.Exists(file_path))
                XmlDocument.Load(file_path);
        }

        private XmlDocument XmlDocument = null;

        public string this[string index]
        {
            get
            {
                if (XmlNodeGetter == null)
                    return string.Empty;

                return XmlNodeGetter(XmlDocument, index);
            }
        }
    }

    public class ConfigurationManager
    {
        public static ConfigSettings AppSettings
        {
            get
            {
                return new ConfigSettings
                {
                    XmlNodeGetter = (document, key) =>
                    {
                        return document.SelectSingleNode(string.Format("/configuration/appSettings/add[@key='{0}']", key))?.Attributes["value"]?.Value;
                    }
                };
            }
        }

        public static ConfigSettings ConnectionStrings
        {
            get
            {
                return new ConfigSettings
                {
                    XmlNodeGetter = (document, key) =>
                    {
                        return document.SelectSingleNode(string.Format("/configuration/connectionStrings/add[@name='{0}']", key))?.Attributes["connectionString"]?.Value;
                    }
                };
            }
        }
    }
}
